<?php


namespace app\api\controller\user;


use app\api\model\user\UserExtract;
use app\api\model\user\UserMoneyRecord;
use app\common\controller\Api;
use think\Db;

/**
 * 我的钱包
 * */
class Wallet extends Api
{
    protected $noNeedLogin = [];

    /**
     * @title 我的钱包页面(GET)
     * @describe 由于需求不明确，余额暂时存在用户表
     * @url api/user.wallet/userWallet
     * */
    public function userWallet()
    {
        $data = [
            'avatar' => $this->auth['avatar'],
            'username' => $this->auth['username'],
            'balance' => $this->auth['balance'],
            'count_consume' => $this->auth['count_consume'],
        ];
        $this->success('获取成功', $data);
    }

    /**
     * @title 个人余额明细记录(GET)
     * @url api/user.wallet/userMoneyRecord
     * @param integer page 页码
     * */
    public function userMoneyRecord()
    {
        $page = $this->request->get('page', 1, 'intval');
        $page = max(1, $page);
        $page = ($page - 1) * 15;
        $recordModel = new UserMoneyRecord();
        $list = $recordModel->where('user_id', $this->auth['id'])->limit($page, 15)->order('id','desc')->select();
        foreach ($list as $row) {
            $row->visible(['id', 'type', 'record_type', 'money', 'balance', 'createtime']);
            if ($row->type == '支出') {
                $row->money = '-' . $row->money;
            } elseif ($row->type == '收入') {
                $row->money = '+' . $row->money;
            }
        }
        $this->success('获取成功', $list);
    }

    /**
     * @title 个人余额明细详情(GET)
     * @url api/user.wallet/userMoneyRecordDetail
     * @param integer record_id 记录ID
     * */
    public function userMoneyRecordDetail()
    {
        $id = $this->request->get('record_id', 0, 'intval') ?: $this->error('请求参数错误');
        $recordModel = new UserMoneyRecord();
        $row = $recordModel->with('business')
            ->where(['user_money_record.id' => $id, 'user_money_record.user_id' => $this->auth['id']])
            ->find();
        if (!$row) {
            $this->error('记录不存在');
        }
        if ($row->type == '支出') {
            $row->money = '-' . $row->money;
        } elseif ($row->type == '收入') {
            $row->money = '+' . $row->money;
        }
        $row->business->visible(['id', 'name']);
        $this->success('获取成功', $row);
    }

    /**
     * @title 个人提现记录(GET)
     * @url api/user.wallet/userExtractRecord
     * */
    public function userExtractRecord()
    {
        $page = $this->request->get('page', 1, 'intval');
        $page = max(1, $page);
        $page = ($page - 1) * 15;
        $extractModel = new UserExtract();
        $list = $extractModel->where(['user_id' => $this->auth['id']])->limit($page, 15)->select();
        foreach ($list as $row) {
            $row->visible(['id', 'money', 'balance', 'type', 'createtime']);
            $row->type = '提现';
        }
        $this->success('获取成功', $list);
    }

    /**
     * @title 个人提现详情(GET)
     * @url api/user.wallet/userExtractRecordDetail
     * @param integer record_id 记录ID
     * */
    public function userExtractRecordDetail()
    {
        $id = $this->request->get('record_id', 0, 'intval') ?: $this->error('请求参数错误');
        $extractModel = new UserExtract();
        $row = $extractModel->where(['id' => $id, 'user_id' => $this->auth['id']])->find();
        $row->type = '提现';
        $this->success('获取成功', $row);
    }

    /**
     * @title 个人提现页面信息获取(GET)
     * @url api/user.wallet/userExtractInfo
     * */
    public function userExtractInfo()
    {
        // 获取用户绑定的银行卡信息
        $bankInfo = Db::name('user_bank')
            ->alias('a')
            ->join('bank_category b','a.bank_id = b.id','left')
            ->where('user_id', $this->auth['id'])
            ->field('a.*,b.name as bankName')
            ->find();
        $data = [
            'userBalance'=>$this->auth['balance']
        ];
        if (!$bankInfo['bankName']) {
            $data['bankInfo'] = ' 您未绑定银行卡，绑定银行卡后才可进行提现';
        } else {
            $data['bankInfo'] = $bankInfo['bankName'].'('.substr($bankInfo['account'],-4).')';
        }
        $this->success('获取成功',$data);
    }

    /**
     *@title 个人提现(POST)
     *@url api/user.wallet/userExtract
     *@param string $money 提现金额
     * */
    public function userExtract()
    {
        $money = $this->request->post('money')?:$this->error('请输入提现金额');
        $money = sprintf("%.2f",$money);
        if ($money<100.00) {
            $this->error('提现金额不能小于100元');
        }
        if ($money>$this->auth['balance']) {
            $this->error('可提现余额不足');
        }
        // 启动事务
        Db::startTrans();
        try{
            // 再次查询可用余额
            $balance = Db::name('user')->where('id',$this->auth['id'])->value('balance');
            if ($money>$balance) {
                exception('可提现余额不足');
            }
            // 流水号
            $record_no = date('YmdHis').rand(1000,9999);
            $data = [
                'user_id'=>$this->auth['id'],
                'money'=>$money,
                'balance'=>$balance-$money, // 只是一个预计余额，但是实际是多少，还以后台审核后为准。
                'record_no'=>$record_no,
                'status'=>'extracting',
                'createtime'=>time()
            ];
            // 插入到提现记录表，如果要扣减余额，需要在后台审核通过后再进行扣减
            $extractModel = new UserExtract();
            $extractModel->insert($data);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功，等待后台审核');
    }
}